package com.eshop.modules.services;

import org.slf4j.LoggerFactory;
import me.chanjar.weixin.mp.bean.material.WxMediaImgUploadResult;
import java.util.List;
import com.eshop.modules.mp.utils.URLUtils;
import cn.hutool.core.util.ReUtil;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import cn.hutool.http.HttpUtil;
import cn.hutool.core.io.FileUtil;
import me.chanjar.weixin.mp.bean.material.WxMpMaterial;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpMassSendResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.api.WxMpService;
import com.eshop.exception.ErrorRequestException;
import me.chanjar.weixin.mp.bean.WxMpMassTagMessage;
import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import com.eshop.modules.mp.config.WxMpConfiguration;
import com.eshop.modules.mp.service.dto.ArticleDto;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class WechatArticleService
{
    private static final Logger log;
    @Value("${file.path}")
    private String uploadDirStr;
    
    public void publish(final ArticleDto wxNewsArticleItem) throws WxErrorException {
        final WxMpService wxMpService = WxMpConfiguration.getWxMpService();
        final WxMpMaterialNews wxMpMaterialNews = new WxMpMaterialNews();
        final WxMpNewsArticle article = new WxMpNewsArticle();
        final WxMpMaterialUploadResult wxMpMaterialUploadResult = this.uploadPhotoToWx(wxMpService, wxNewsArticleItem.getImageInput());
        wxNewsArticleItem.setThumbMediaId(wxMpMaterialUploadResult.getMediaId());
        article.setAuthor(wxNewsArticleItem.getAuthor());
        final String content = this.processContent(wxMpService, wxNewsArticleItem.getContent());
        System.out.println(content);
        article.setContent(content);
        article.setContentSourceUrl(wxNewsArticleItem.getUrl());
        article.setDigest(wxNewsArticleItem.getSynopsis());
        article.setShowCoverPic(true);
        article.setThumbMediaId(wxNewsArticleItem.getThumbMediaId());
        article.setTitle(wxNewsArticleItem.getTitle());
        wxMpMaterialNews.addArticle(article);
        WechatArticleService.log.info("wxMpMaterialNews : {}", JSONUtil.toJsonStr(wxMpMaterialNews));
        final WxMpMaterialUploadResult wxMpMaterialUploadResult2 = wxMpService.getMaterialService().materialNewsUpload(wxMpMaterialNews);
        final WxMpMassTagMessage massMessage = new WxMpMassTagMessage();
        massMessage.setMsgType("mpnews");
        massMessage.setMediaId(wxMpMaterialUploadResult2.getMediaId());
        massMessage.setSendAll(true);
        final WxMpMassSendResult massResult = wxMpService.getMassMessageService().massGroupMessageSend(massMessage);
        if (!"0".equals(massResult.getErrorCode())) {
            WechatArticleService.log.info("error:" + massResult.getErrorMsg());
            throw new ErrorRequestException("发送失败");
        }
        WechatArticleService.log.info("massResult : {}", JSONUtil.toJsonStr(massResult));
        WechatArticleService.log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMpMaterialUploadResult2));
    }
    
    private WxMpMaterialUploadResult uploadPhotoToWx(final WxMpService wxMpService, String picPath) throws WxErrorException {
        final WxMpMaterial wxMpMaterial = new WxMpMaterial();
        final String filename = String.valueOf((int)System.currentTimeMillis()) + ".png";
        final String downloadPath = this.uploadDirStr + filename;
        final long size = HttpUtil.downloadFile(picPath, FileUtil.file(downloadPath));
        picPath = downloadPath;
        final File picFile = new File(picPath);
        wxMpMaterial.setFile(picFile);
        wxMpMaterial.setName(picFile.getName());
        WechatArticleService.log.info("picFile name : {}", picFile.getName());
        final WxMpMaterialUploadResult wxMpMaterialUploadResult = wxMpService.getMaterialService().materialFileUpload("image", wxMpMaterial);
        WechatArticleService.log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMpMaterialUploadResult));
        return wxMpMaterialUploadResult;
    }
    
    private String processContent(final WxMpService wxMpService, String content) throws WxErrorException {
        if (StringUtils.isBlank((CharSequence)content)) {
            return content;
        }
        final String imgReg = "<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
        final List<String> imgList = (List<String>)ReUtil.findAllGroup1(imgReg, (CharSequence)content);
        for (int j = 0; j < imgList.size(); ++j) {
            final String imgSrc = imgList.get(j);
            String filepath = URLUtils.getParam(imgSrc, "filepath");
            if (StringUtils.isBlank((CharSequence)filepath)) {
                final String filename = System.currentTimeMillis() + ".png";
                final String downloadPath = this.uploadDirStr + filename;
                final long size = HttpUtil.downloadFile(imgSrc, FileUtil.file(downloadPath));
                filepath = downloadPath;
            }
            final WxMediaImgUploadResult wxMediaImgUploadResult = wxMpService.getMaterialService().mediaImgUpload(new File(filepath));
            content = StringUtils.replace(content, (String)imgList.get(j), wxMediaImgUploadResult.getUrl());
        }
        return content;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)WechatArticleService.class);
    }
}
